import axios from "axios";
import NProgress from "nprogress";
import { Toast } from "vant";
import "nprogress/nprogress.css";
import { getToken } from "./tools";
export const serverUrl = "http://121.40.154.196:8080";
const instance = axios.create({
  baseURL: serverUrl, // 请求的基础地址
  timeout: 5000, // 请求超时时间
});

// Add a request interceptor
// 全局请求拦截，发起网络请求之前执行
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    NProgress.start(); // 显示loading

    config.headers.Authorization = getToken();
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
// 全局响应拦截，网络请求返回之后执行
instance.interceptors.response.use(
  function (response) {
    NProgress.done(); // 隐藏loading
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  },
  function (error) {
    NProgress.done();
    console.dir(error);
    // if (error.response?.status == 401) {
    //   Toast.fail("请先登录");
    //   window.location.href = "/#/login"; // 跳转到登录页
    // }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

/**
 * 发起一个get请求
 * @param {*} url     地址
 * @param {*} params  url中传递的参数
 * @returns
 */
export const get = (url, params) =>
  instance.get(url, {
    params, // 表示url中传递的参数
  });

/**
 * 发起post请求
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const post = (url, data) => instance.post(url, data);

/**
 * 发起put请求
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const put = (url, data) => instance.put(url, data);

/**
 * 发起Delete请求
 * @param {*} url 地址
 * @param {*} data  数据
 * @returns
 */
export const Delete = (url) => instance.delete(url);

export default instance;
